#!/usr/local/bin/python
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response

from assoce.core.models import Emprunt, Membre, Item, Activite
from django.http import HttpResponseRedirect, HttpResponse
from datetime import datetime
from django.forms.models import modelform_factory
from django.views.generic.simple import direct_to_template

from django.contrib.auth.decorators import login_required

@login_required
def index(request, activite_name, template='materiel/index.html'):
    membre = Membre.objects.get(user=request.user)
    emprunts = Emprunt.objects.filter(membre=membre, end__isnull=True)
    activite = Activite.objects.get(label=activite_name)
    
    context = {'emprunts':emprunts, 'activite_label':activite_name}
    fields = ['start',]
    
    if activite.is_manager(request.user):
        context['manager'] = True
        fields.append('membre')
        context['sortis'] = Emprunt.objects.filter(end__isnull=True, item__activite=activite)

    form = modelform_factory(model=Emprunt, fields=fields)
    
    if request.method == 'POST':
        form = form(request.POST)
        res = []
        if request.POST.has_key('search'):
            s = request.POST['search_str']
            q = Item.objects.filter(label__icontains=s, activite=activite)
            res = list(q)
        if request.POST.has_key('action'):
            if request.POST['action'] == u'Réserver':
                _reserver(request.POST, form)
                return HttpResponseRedirect('')
        context.update({'form':form, 'items':res})
    else:
        data = {'membre':request.user.id, 'start': datetime.now()}
        context.update({'form':form(data)})
    #return render_to_response(template, context)
    return direct_to_template(request, template, extra_context=context)

def retour(req, activite_name, id):
    id = int(id)
    
    activite = Activite.objects.get(label=activite_name)
    if not activite.is_manager(req.user):
        raise Exception("Seul le manager %s peut enregistrer un retour" % activite_name)
    emp = Emprunt.objects.get(id=id)
    if not emp.end:
        emp.end = datetime.now()
        emp.save()
        req.user.message_set.create(message='Le retour a été enregistré correctement.')
    return HttpResponseRedirect('../../#sortis')
    
def _reserver(post, emprunt_form):
    emprunt_form.is_valid()
    data = emprunt_form.cleaned_data
    for k,value in post.iteritems():
        if value[0] == 'on':
            try:
                id = int(k)
                item = Item.objects.get(id=id)
                e = Emprunt(**data)
                e.item = item
                e.save()
            except Exception, v:
                raise
    return

@login_required
def reserver(request, activite_name, id, template='materiel/reserver.html'):
    membre = Membre.objects.get(user=request.user)
    emprunts = Emprunt.objects.filter(membre=membre, end__isnull=True)
    activite = Activite.objects.get(label=activite_name)
    
    context = {'emprunts':emprunts, 'activite_label':activite_name}
    fields = ['start',]
    
    if activite.is_manager(request.user):
        context['manager'] = True
        fields.append('membre')

    form = modelform_factory(model=Emprunt, fields=fields)
    
    if request.method == 'POST':
        form = form(request.POST)
        res = []
        if request.POST.has_key('search'):
            s = request.POST['search_str']
            q = Item.objects.filter(label__icontains=s, activite=activite)
            res = list(q)
        if request.POST.has_key('action'):
            if request.POST['action'] == u'Réserver':
                _reserver(request.POST, form)
                return HttpResponseRedirect('')
        context.update({'form':form, 'items':res})
    else:
        data = {'membre':request.user.id, 'start': datetime.now()}
        context.update({'form':form(data)})
    #return render_to_response(template, context)
    return direct_to_template(request, template, extra_context=context)
